package com.one.group.admin.dao.impl;

import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.convert.Convert;
import com.one.group.admin.dao.AdvertDao;
import com.one.group.admin.dao.ChargeInfoDao;
import com.one.group.model.entity.ChargeInfo;
import lombok.Data;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.aggregation.Aggregation;
import org.springframework.data.mongodb.core.aggregation.AggregationResults;
import org.springframework.data.mongodb.core.aggregation.GroupOperation;
import org.springframework.data.mongodb.core.mapping.Field;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.stereotype.Repository;

@Repository
public class ChargeInfoDaoImpl implements ChargeInfoDao {
    @Autowired
    private MongoTemplate mongoTemplate;
    @Override
    public Boolean insertChargeInfo(ChargeInfo chargeInfo) {
        try {
            mongoTemplate.save(chargeInfo);
            return true;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public Double getTotalAmount() {
        // 获取租户id
        Long tenant_id = Convert.toLong(StpUtil.getExtra("tenant_id"));
        try {
            Aggregation aggregation = Aggregation.newAggregation(
                    Aggregation.match(Criteria.where("tenantId").is(tenant_id)),
                    Aggregation.group().sum("amount").as("totalAmount"),
                    Aggregation.project("totalAmount").andExclude("_id")
            );
            AggregationResults<TotalAmountResult> results = mongoTemplate.aggregate(aggregation, "chargeInfo", TotalAmountResult.class);
            TotalAmountResult totalAmountResult = results.getUniqueMappedResult();
            return totalAmountResult != null ? totalAmountResult.getTotalAmount() : 0.0;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
    // 内部类用于接收聚合结果
    @Data
    private static class TotalAmountResult {
        @Field("totalAmount")
        private Double totalAmount;
    }

}
